package com.gxgeek.springdata.common.util;

import lombok.Cleanup;
import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
import java.io.InputStream;
import java.sql.*;
import java.util.Properties;

/**
 * Created by gx on 2017/4/21.
 */
@Slf4j
public class JDBCUtil {
    private static  final String url;
    private static  final String username ;
    private static  final String password ;
    //读取配置文件
    static {
        Properties properties = new Properties();
        try {
            @Cleanup InputStream inputStream = JDBCUtil.class.getClassLoader().getResourceAsStream("db.properties");
            properties.load(inputStream);
        } catch (IOException e) {
            log.error("读取配置文件失败"+e.getMessage(),e);
        }
        url = properties.getProperty("jdbc.url");
        username = properties.getProperty("jdbc.username");
        password = properties.getProperty("jdbc.password");
    }

    /**
     * 获得连接
     * @return
     * @throws SQLException
     */
    public static Connection getConnection() throws SQLException {
        return DriverManager.getConnection(url,username,password);
    }


    /**
     * 清理资源
     * @param resultSet
     * @param statement
     * @param connection
     */
    public static void relesase(ResultSet resultSet , Statement statement,Connection connection){
        if (resultSet!=null){
            try {
                resultSet.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        if (statement!=null){
            try {
                statement.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        if (connection!=null){
            try {
                connection.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }







}
